<?php

/**
 * 合同控制器
 * @author wangwx 2015-5-7
 */

namespace mybackend\controllers;

use common\entities\common\MyscrmOrganizationToAuthorizeEntity;
use common\repositories\common\MyscrmContractRepository;
use common\repositories\myhtsq\ContractReceivableRepository;
use common\services\common\MyscrmContractManageService;
use Yii;
use common\services\myhtsq\ContractService;
use common\entities\myhtsq\ActionCode;
use common\support\CacheManage;
use yii\filters\AccessControl;
use common\support\OSSUploader;
use common\support\CFileUploader;
use common\error\ErrorCode;
use common\services\myhtsq\ContractReceivableService;
use common\entities\ContractEntity;
use common\repositories\myhtsq\ContractManageRepository;
use common\entities\myhtsq\ContractApplicationEntity;
use common\repositories\common\MyscrmApplicationRepository;
use common\services\common\MyscrmContractApplicationService;
use common\repositories\myhtsq\ContractApplicationRepository;
use common\services\myhtsq\ErpInterfaceService;
use common\repositories\myhtsq\ContractPaymentRepository;
use common\entities\myhtsq\ApplicationInfoEntity;
use common\repositories\common\MyscrmContractSyncDeleteDataRepository;
use common\entities\myhtsq\MyscrmContractDistributionAmountEntity;
use common\entities\myhtsq\ContractPropertyEntity;
use common\services\myhtsq\RevenueService;
use common\services\myhtsq\LogService;
use common\models\myhtsq\ContractApiLogModel;
use common\repositories\myhtsq\RevenueRecognitionRepository;



class ContractController extends BaseController
{

    protected $_contractService;
    protected $_revenueService;
    protected $_logService;

    public function __construct($id, $module, ContractService $contractService, RevenueService $revenueService, LogService $logService,$config = [])
    {
        $this->_contractService = $contractService;
        $this->_revenueService = $revenueService;
        $this->_logService = $logService;
        parent::__construct($id, $module, $config);
    }

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['authorization-expired-remind'],
                        'allow' => true,
                    ],
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ]
        ];
    }

    protected function roleAuthRules()
    {
        return [
            'actions' => ['AddContract', 'AuditReview', 'CancelContract', 'CancelReview', 'ExportBalanceContractListExecl',
                'SubmitRevenue', 'SubmitReview', 'UpdateContract', 'UpdateContractAccount',
                'SaveSignDely', 'ExportMyContract', 'ExportContract'],
            'rules' => [
                [
                    'allow' => true,
                    'actionCodeMaps' => [
                        'AddContract' => ActionCode::CONTRACT_MNG,
                        'AuditReview' => ActionCode::CONTRACT_APPROVE,
                        'CancelContract' => ActionCode::CONTRACT_MNG,
                        'CancelReview' => ActionCode::CONTRACT_MNG,
                        'ExportBalanceContractListExecl' => ActionCode::HT_EXPORT,
                        'SubmitRevenue' => ActionCode::REVENUE_MOD,//修改收入
                        'SubmitReview' => ActionCode::CONTRACT_MNG,
                        'UpdateContract' => ActionCode::CONTRACT_MNG,
                        'UpdateContractAccount' => ActionCode::CONTRACT_MNG,
                        'SaveSignDely' => ActionCode::CONTRACT_VIEW,
                        'ExportContract' => ActionCode::HT_EXPORT,
                        'ExportMyContract' => ActionCode::HT_EXPORT,
                    ]
                ]
            ]
        ];
    }

    public $ykPropertyId = [
            ContractPropertyEntity::MYYK_PROPERTY_DIRECTLY_UNDER_ID,//云客签约-直属
            ContractPropertyEntity::MYYK_PROPERTY_JOINT_OPERATION_ID,//云客签约-直属区域
            ContractPropertyEntity::MYYK_PROPERTY_DIRECT_SALES_ID,//云客直销
        ];

    /**
     * 新建合同
     */
    public function actionAddContract()
    {
        $this->exitIfNotPost();
        $contract = $this->getParam('contract', 'post'); //合同内容
        $productArr = $this->getParam('product', 'post'); //产品数组
        $principalArr = $this->getParam('principal', 'post'); //负责人数组
        $data = $this->_contractService->addContract($contract, $productArr, $principalArr);

        //新增业绩
        $contractPropertyId = $contract['contract_property_id'];
        if(in_array($contractPropertyId,$this->ykPropertyId)&&($data)){

            $contractModel = ContractManageRepository::getContractManageModelByContractId($data); //获取model
            $contractModel->balance_amount = $contractModel->income_amount;
            $contractModel->save();
            //删除业绩
            $this->_contractService->deleteAllByContractId($data);
            $this->_contractService->actionUpdateAchievementForYk($data);
            $this->_contractService->achievementGrouping($data);//4
        }

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 是否为云客合同
     */
    public function IsYkContract($contractId)
    {
        $contractPropertyId = $this->_contractService->getContractNature($contractId);
        return in_array($contractPropertyId,$this->ykPropertyId);
    }

    /**
     * 更新合同
     */
    public function actionUpdateContract()
    {
        $this->exitIfNotPost();
        $contract = $this->getParam('contract', 'post'); //合同内容
        $productArr = $this->getParam('product', 'post'); //产品数组
        $principalArr = $this->getParam('principal', 'post'); //负责人数组
        $saveType = $this->getParam('save_type', 'post', ""); //多个保存的情况都是调用此接口,区分产品的情况

        if (empty($contract['contract_id'])) {//合同id是否为空
            $this->errorParam();
        }

        $data = $this->_contractService->updateContract($contract, $productArr, $principalArr);

        $IsYk = $this->IsYkContract($contract['contract_id']);

        //更新成功之后需要重新计算产品的结算金额等
        if (false !== $data) {
            $isForce = true;
            if ($saveType == "product") {
                $isForce = false;
            }
            //业务逻辑改变注释原逻辑 坏味道提示 
            //$this->_contractService->calcApplicationAmount($contract['contract_id'], $isForce,$IsYk);
        }

        if($IsYk){
            //删除业绩
            $this->_contractService->deleteAllByContractId($data);
            //新增业绩
            //业务逻辑改变注释原逻辑 坏味道提示
            $this->_contractService->actionUpdateAchievementForYk($data);
            $this->_contractService->achievementGrouping($data);//4
        }



        $this->_contractService->achievementGrouping($contract['contract_id']);
        $sumPayment = ContractPaymentRepository::getPaymentSumByContractId($contract['contract_id']);

        $entity = new MyscrmContractDistributionAmountEntity();
        $editAchievement = $entity::find()->where(['contract_id'=>$contract['contract_id']])->all();

        $SummaryAchievement = 0;
        foreach ($editAchievement as $item){
            $SummaryAchievement+=(int)$item['settlement_average_amount'];
        }

        $SummaryAchievement = empty($SummaryAchievement)?1:$SummaryAchievement;//防止被除数为0

        foreach ($editAchievement as $item){
            $item->receivable_average_amount = round($sumPayment)*$item->settlement_average_amount/$SummaryAchievement;
            $res =$item->save();
        }

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }



    /**
     * 更新业绩
     * @author zhoud01
     * @since 2017-8-11
     */
    public function actionUpdateAchievement()
    {
        $contract = $this->getParam('contract', 'post'); //合同内容
        $productArr = $this->getParam('product', 'post'); //产品数组

        ContractPaymentRepository::getPaymentSumByContractId($contract['contract_id']);
        $SummaryAchievement = 0;

        $configDataBase = ContractEntity::getDb();
        $trans = $configDataBase->beginTransaction();
        try{

            foreach ($productArr as $arr){

                //坏味道修复

                $SummaryAchievement += $arr['settlement_average_amount'];
                $data = $this->_contractService->addAuthorizationAchievement($arr,$contract);
                if($data === false){
                    $trans->rollBack();
                    $data = false;
                    $Code  = 400;
                    $Msg = '业绩增加失败';
                    $this->exportJson($data,$Code,$Msg);
                    return false;
                }
            }

            //坏味道修复
            $addAchievement = $this->_contractService->achievementGrouping($contract['contract_id']);
            if($addAchievement === false){
                $trans->rollBack();
                $data = false;
                $Code  = 400;
                $Msg = '业绩汇总失败';
                $this->exportJson($data,$Code,$Msg);
                return false;
            }

            $addAchievement = $this->_contractService->achievementSettlementAmount($contract['contract_id']);
            if($addAchievement === false){
                $trans->rollBack();
                $data = false;
                $Code  = 400;
                $Msg = '已结算金额合计失败';
                $this->exportJson($data,$Code,$Msg);
                return false;
            }


            $trans->commit();
        }catch(\Exception $e){
            $trans->rollBack();
            return false;
        }

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }


    /**
     * 获取合同基本信息与签约产品信息
     */
    public function actionGetContractInfo($contractId = '')
    {
        if (empty($contractId)) {
            $this->errorParam();
        }
        $data = $this->_contractService->getContractInfo($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 提交合同复核
     */
    public function actionSubmitReview()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post'); //合同内容
        if (empty($contractId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->submitReview($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 撤销合同复核
     */
    public function actionCancelReview()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post'); //合同内容
        if (empty($contractId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->cancelReview($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 合同复核
     */
    public function actionAuditReview()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post'); //合同内容
        if (empty($contractId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->auditReview($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 根据性质id,获取帐套公司列表
     * @param string $propertyId 性质id
     * @return array
     */
    public function actionGetContractAccountCompanyList($propertyId = '')
    {
        if (empty($propertyId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->getContractAccountCompanyList($propertyId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 根据性质id,获取签署公司列表
     * @param string $propertyId 性质id
     * @return array
     */
    public function actionGetContractCompanyList($propertyId = '')
    {
        if (empty($propertyId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->getContractCompanyList($propertyId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取服务机构列表
     * @param string $propertyId 性质id
     * @return array
     */
    public function actionGetAgencyCompanyList()
    {
        $data = $this->_contractService->getAgencyCompanyList();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 作废合同
     */
    public function actionCancelContract()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post'); //合同内容
        if (empty($contractId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->cancelContract($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 合同列表
     * @param integer     $pageIndex 页码
     * @param integer     $pageSize  页条数
     * @param string      $sortBy    排序字段
     * @param bool|string $sortAsc   是否升序
     * @param int         $status    合同状态  合同状态:0：草稿,1：提交复核,2：已审核  -1作废
     * @param int         $category  合同小类查询
     * @param null|string $property  合同性质
     * @param string      $keyword   关键字
     * @param integer     $areaId    区域id
     * @param int         $timeType
     * @param string      $beginDate
     * @param string      $endDate
     */
    public function actionGetContractList($pageIndex = 1, $pageSize = 10, $sortBy = null, $sortAsc = '', $status = null,$category = 0, $property = null, $keyword = null, $areaId = null, $timeType = 0, $beginDate = '', $endDate = '')
    {
        $data = $this->_contractService->getContractList($pageIndex, $pageSize, $sortBy, $sortAsc, $status, $property, $keyword, $areaId, '', $timeType, $beginDate, $endDate,$category);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取结算合同列表
     * @param integer $pageIndex 页码
     * @param integer $pageSize 页条数
     * @param string $sortBy 排序字段
     * @param int $status 结算状态 0：未结算 1：已结算
     * @param string $property 合同性质id
     * @param string $sortBy 排序字段
     * @param boolean $sortAsc 是否升序
     * @param integer $areaId 区域id
     * @param string $keyword 关键字
     * @param string $beginDate 结算开始时间
     * @param string $endDate 结算结束时间
     */
    public function actionGetBalanceContractList($pageIndex = 1, $pageSize = 10, $sortBy = null, $sortAsc = '', $status = null, $property = null, $keyword = null, $areaId = null, $beginDate = null, $endDate = null)
    {
        $data = $this->_contractService->getBalanceContractList($pageIndex, $pageSize, $sortBy, $sortAsc, $status, $property, $keyword, $areaId, $beginDate, $endDate);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 导出未结算合同
     * @param boolean $property 合同性质
     * @param integer $areaId 区域id
     * @param string $keyword 关键字
     * @param string $beginDate 结算开始时间
     * @param string $endDate 结算结束时间
     */
    public function actionExportBalanceContractListExecl()
    {
        $property = $this->getParam('property', 'post');
        $keyword = $this->getParam('keyword', 'post');
        $areaId = $this->getParam('areaId', 'post');
        $beginDate = $this->getParam('beginDate', 'post');
        $endDate = $this->getParam('endDate', 'post');
        $data = $this->_contractService->exportBalanceContractListExecl($property, $keyword, $areaId, $beginDate, $endDate);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 导入合同结算状态
     */
    public function actionImportBalanceContractListExecl()
    {
        $data = $this->_contractService->importBalanceContractListExecl();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同城市区域列表
     */
    public function actionGetContractAreaList()
    {
        $data = $this->_contractService->getContractAreaList();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取收入信息数据
     */
    public function actionGetContractRevenue()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        if (empty($contractId)) {
            $this->errorParam();
        }
        $data = $this->_contractService->getContractRevenue($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 处理保存收入信息数据
     */
    public function actionSubmitRevenue()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post'); //合同id
        $revenueList = $this->getParam('revenueList', 'post'); //收入信息
        $accountCompanyId = $this->getParam('accountCompanyId', 'post'); //帐套公司id

        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        try{
            $revenueId = $this->_contractService->submitRevenue($contractId, $accountCompanyId, $revenueList);
        }catch (\Exception $e){
            $this->exportJson(false, -1, $e->getMessage());
        }
        $data = $this->_contractService->getContractRevenueByRevenueId($revenueId,$contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 保存结算与返款信息
     */
    public function actionUpdateContractAccount()
    {
        $this->exitIfNotPost();
        $postData = \Yii::$app->request->post(); //获取所有提交数据
        if (empty($postData) || empty($postData['contract_id'])) {//是否传值为空
            $this->errorParam();
        }

        $data = $this->_contractService->updateContractAccount($postData);

        //更新成功之后需要重新计算产品的结算金额等
        if (false !== $data) {
            $this->_contractService->calcApplicationAmount($postData['contract_id'], true);
        }

        //判断是否为云客类

        $IsYk = $this->IsYkContract($postData['contract_id']);

        if($IsYk){

            //删除业绩
            $this->_contractService->deleteAllByContractId($postData['contract_id']);
            //新增业绩
            $this->_contractService->actionUpdateAchievementForYk($postData['contract_id']);

            //业绩分组处理
            $this->_contractService->achievementGrouping($postData['contract_id']);//4

        }


        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    public function actionSaveDistributionAmount()
    {
        $this->exitIfNotPost();
        $postData = \Yii::$app->request->post(); //获取所有提交数据
        if (empty($postData) || empty($postData['distribution']) || empty($postData['contract_id']) || empty($postData['input_date'])) {//是否传值为空
            $this->errorParam();
        }

        $sumPayment = ContractPaymentRepository::getPaymentSumByContractId($postData['contract_id']);//回款总额

        $receivable_average_amount = 0;
        $settlement_average_amount = 0;

        foreach ($postData['distribution'] as $item){
            $receivable_average_amount += $item['receivable_average_amount'];
            $settlement_average_amount += $item['settlement_average_amount'];
        }
        
        if(round($receivable_average_amount) !== round($sumPayment)){
            $data = false;
            $Code  = 400;
            $Msg = '回款业绩分摊金汇总不等于回款总金额';
            $this->exportJson($data,$Code,$Msg);
        }


        $data = $this->_contractService->saveDistributionAmount($postData['contract_id'], $postData['input_date'], $postData['distribution']);

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取签约分摊金额、结算分摊金额、回款分摊金额列表
     */
    public function actionGetDistributionAmount()
    {
        $contractId = $this->request->get('contractId', '');

        $data = $this->_contractService->getDistributionAmount($contractId);

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取结算与返款信息数据
     */
    public function actionGetContractBalanceInfo()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $data = $this->_contractService->getContractBalanceInfo($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同开通信息
     */
    public function actionGetContractOrganizationInfo()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $data = $this->_contractService->getContractOrganizationInfo($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }


    /**
     * @sine 2017-6-14
     * @auth zhoud01@mingyuanyun.com
     * 获取广告消耗信息
     */
    public function actionGetAdOrganizationInfo($flag=null,$contractId=null,$toGet = false)
    {

        if(Yii::$app->request->isGet){
            $contractId = $this->getParam('contractId', 'get');
        }

        $data['AdList'] = $this->_contractService->getAdOrganizationInfo($contractId);

        $baseData = $this->_contractService->getContractInfo($contractId);

        //littler_category_id:"62f81rt6-fcf4-11e4-bed8-00155d02c832"
        //广告投放金额
        $rent_amount = $baseData['contract']['rent_amount'];
        //广告服务费
        $delivery_amount = $baseData['contract']['delivery_amount'];

        $idAndPrice = [];
        $idAndPath = [];
        $amount = 0;

        if(!empty($data['AdList'])){
            foreach ($data['AdList'] as $k=>$v){

                $idAndPrice[$v['Id']] =$v['Money'];
                $idAndPath[$v['Id']] =$v['DownloadUrl'];
                unset($data['AdList'][$k]['DownloadUrl']);
                $data['AdList'][$k]['Time'] = isset($data['AdList'][$k]['Time']) ? $data['AdList'][$k]['Time']*1000 : 0;
                $data['AdList'][$k]['Money'] = round($data['AdList'][$k]['Money']*100)/100;//解决精度显示问题
                $amount +=$v['Money'];
                //云客租用服务”时，投放明细，新增界面字段“投放金额”值应该为0 彭涛提出
                if($baseData['contract']['littler_category_id'] === '62f81bf4-fcf4-11e4-bed8-00155d02c832'){//云客租用
                    $data['AdList'][$k]['Money'] = 0;
                    $amount = 0;
                }
            }

            #获取合同下广告总金额,广告投放金额,广告服务费
            $data['amount'] = $amount;
            $data['rent_amount'] = $rent_amount;
            $data['delivery_amount'] = $delivery_amount;


            #广告消耗金额,总消耗金额,广告投放金额,广告服务费
            $MoneyList =[
                'idAndPrice'=>$idAndPrice,
                'amount'=>$amount,
                'rent_amount'=>$rent_amount,
                'delivery_amount'=>$delivery_amount,
            ];

        }else{
            #如果没有广告消耗产生那么消耗金额和总消耗金额为0
            $MoneyList =[
                'idAndPrice'=>0,
                'amount'=>0,
                'rent_amount'=>$rent_amount,
                'delivery_amount'=>$rent_amount,
            ];
        }

        if($flag){
            return $MoneyList;
        }

        if($baseData['contract']['littler_category_id'] === '62f81ca9-fcf4-11e4-bed8-00155d02c832'){//云客增值服务 彭涛提出
            $data = [];
        }

        if($toGet){
            return $data['AdList'];
        }

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());

    }


    /**
     * 文档上传
     * @return string
     */
    public function actionUploadDocument($upload =null){

        $ret = $this->uploadDocument("file");

        if($upload){
            return $ret;
        }

        return $this->json($ret);
    }

    /**
     * 根据配置区域不同的文档uploader对象
     * @param type $httpFile
     * @return \common\support\CFileUploader
     */
    private function getDocumentUploader($httpFile){
        $type = "file";
        $rootPath = "/upfiles";
        if(isset(Yii::$app->params["uploader"]) && isset(Yii::$app->params["uploader"]["type"])){
            $type = Yii::$app->params["uploader"]["type"];
            $rootPath = Yii::$app->params["uploader"]["rootPath"];
        }
        $uploader = null;
        $imageSize = 1024*1024*100; //文档大小限制为20M
        $contentType = [];
        if($type == 'oss'){
            $uploader = new OSSUploader($imageSize,$contentType,$httpFile,$rootPath);
        }
        else{
            $uploader = new CFileUploader($imageSize,$contentType,$httpFile,str_replace('\\','/',dirname(dirname(__DIR__)).'/web'),$rootPath);
        }

        return $uploader;
    }

    /**
     * 上传文档
     * @param type $fieldName
     * @return type
     */
    private function uploadDocument($fieldName){
        if(!isset($_FILES[$fieldName])){
            return array(
                "retCode"=>199003,//无效的输入
                "errMsg"=>"无上传数据，原因可能是文件大小超出php.ini的post_max_size设置值。"
            );
        }

        if($_FILES["file"]["error"]>0){
            $error_msg = '';
            switch ($_FILES["file"]["error"])
            {
                case 1:
                    $error_msg = '上传文件大小超过php.ini中upload_max_filesize 选项限制的值';
                    break;
                case 2:
                    $error_msg = '上传文件大小超过 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
                    break;
                case 3:
                    $error_msg = '文件只有部分被上传';
                    break;
                case 4:
                    $error_msg = '没有文件被上传';
                    break;
                default:
                    $error_msg = '错误码为'.$_FILES["file"]["error"];
            }
            return array(
                "retCode"=>199003,//无效的输入
                "errMsg"=>$error_msg
            );
        }

        $tmp_name = explode('.',$_FILES['file']['name']);

        $ectension = array_pop($tmp_name);

        $ectension = strtolower($ectension);

        $allowEctension = ['pdf','jpg','png'];

        $uploader = $this->getDocumentUploader($_FILES[$fieldName]);
        //检测文件格式
        if(!in_array($ectension,$allowEctension)){
            return array(
                "retCode"=>199002,
                "errMsg"=>"文件格式不正确"
            );
        }
        //检测文件大小
        if(!$uploader->checkFileSize()){
            return array(
                "retCode"=>199001,//文件超出大小限制
                "errMsg"=>"文件大小不能超过100M"
            );
        }

        $url = $uploader->upload();
        return array(
            "retCode"=>ErrorCode::SUCCESS,
            "data"=>array(
                "path"=>urldecode($url),
            )
        );
    }

    /**
     * @sine 2017-6-14
     * @auth zhoud01@mingyuanyun.com
     * 删除PDF
     */
    public function actionDelAdPdf($id=null){

        $contractId = $this->getParam('contractId');
        $Id = $this->getParam('Id');

        $data = null;
        if(!empty($Id)){

            $data = $this->_contractService->getAdOrganizationInfo($contractId);
            $downloadList = [];

            foreach ($data as $k=>$v){
                $downloadList[$v['Id']] =$v['DownloadUrl'];
            }

            //验证id是否存在
            if(!array_key_exists($Id,$downloadList)){
                //$data = ['retCode'=>'400','errMsg'=>'Id不存在'];
                $Code = 400;
                $Msg = '该合同下Id'.$Id.'不存在';
                $this->exportJson($data,$Code, $Msg);
            }

            if(!$filePath = $downloadList[$Id]){

                $Code = 400;
                $Msg = '没有上传文件';
                $this->exportJson($Code, $Msg);
            }

            $this->actionEditAdList($Id);

        }else{

            $Code = 400;
            $Msg = '缺少id参数';
            $this->exportJson($data,$Code,$Msg);
        }

    }

    /**
     * @sine 2017-6-15
     * @auth zhoud01@mingyuanyun.com
     * 下载PDF
     */
    public function actionDownloadPdf()
    {

        $contractId = $this->getParam('contractId');
        $Id = $this->getParam('Id');
        $type = $this->getParam('type');

        $data = [];

        if(!empty($Id)){

            $data = $this->_contractService->getAdOrganizationInfo($contractId);
            $downloadList = [];

            foreach ($data as $k=>$v){
                $downloadList[$v['Id']] =$v['DownloadUrl'];
            }

            //验证id是否存在
            if(!array_key_exists($Id,$downloadList)){
                //$data = ['retCode'=>'400','errMsg'=>'该合同下没有这个Id'];
                $Code = 400;
                $Msg = '该合同下Id'.$Id.'不存在';
                $this->exportJson($Code, $Msg);
            }

            if(!$filePath = $downloadList[$Id]){
                //$data = ['retCode'=>'400','errMsg'=>'没有上传文件'];
                $Code = 400;
                $Msg = '没有上传文件';
                $this->exportJson($Code, $Msg);
            }

            $filePath = $downloadList[$Id];

            $fileExists = @file_get_contents($filePath, null, null, -1, 1) ? true : false;

            if(!$fileExists){
                $Code = 400;
                $Msg = '文件不存在';
                $this->exportJson($Code, $Msg);
            }

            #获取扩展名
            $str = explode('.',$filePath);
            $extension = end($str);

            if($type == 'view'){
                if($extension == 'pdf'){

                    if($extension =='pdf'){
                        header('Content-type: application/'.$extension);
                        header('filename='.$filePath);
                        readfile($filePath);
                    }
                    exit;
                }

                $imgType = ['jpg','png'];

                if(in_array($extension,$imgType)){//预览img

                    if($extension) {
                        $img = file_get_contents($filePath);
                        header('Content-type: image/' . $extension);
                        echo $img;
                    }
                    exit;
                }
            }

            header("location:".$filePath);


            //return Yii::$app->response->sendFile($filePath,basename($filePath));

        }else{
            $Code = 400;
            $Msg = '缺少id';
            $this->exportJson($data,$Code, $Msg);
        }

    }

    /**
     * @sine 2017-6-15
     * @auth zhoud01@mingyuanyun.com
     * 增加广告记录
     */
    public function actionAddAdList($data=null)
    {

        $this->getParam('Id');
        $contractId = $this->getParam('contractId');
        //$Time =  $this->getParam('Time','post');

        $startOn = $this->getParam('startOn','post');
        $endOn = $this->getParam('endOn','post');

        $Money =  $this->getParam('Money','post');

        $DownloadUrl = null;
        $SaveName = null;
        $FileName = null;

        $baseData = $this->_contractService->getContractInfo($contractId);

        $ServiceType = [
            '62f81bf4-fcf4-11e4-bed8-00155d02c832',//云客租用
            '62f81ca9-fcf4-11e4-bed8-00155d02c832'////云客增值服务 彭涛提出
        ];

        if(in_array($baseData['contract']['littler_category_id'],$ServiceType)){//云客租用
            //有漏洞,改合同属性就可以增加
            $data  = false;
            $Code  = 400;
            $Msg = '云客租用,云客增值服务类合同不可以增加广告投放';
            $this->exportJson($data,$Code,$Msg);
        }

        if(!empty($_FILES)){
            if($_FILES['file']['error']['file'] == UPLOAD_ERR_OK){//上传成功
                $uploadData = $this->actionUploadDocument('add');

                $DownloadUrl = (empty($uploadData['data']['path'])?null:$uploadData['data']['path']);
                $SaveName = basename($DownloadUrl);
                $FileName = $_FILES['file']['name'];

            }
        }

        //坏味道修复
        $startOn = $startOn?strtotime($startOn):time();
        $endOn = $startOn?strtotime($endOn):time();

        $arr = [
            [
                //坏味道修复
                'startOn'=>$startOn,
                'endOn'=>$endOn,
                'Money'=>$Money,
                'DownloadUrl'=>$DownloadUrl,
                'SaveName'=>$SaveName,
                'FileName'=>$FileName,
            ],
        ];


        $addDrained = 0;

        foreach ($arr as $k=>$v){
            $addDrained+=$v['Money'];
        }

        $MoneyList = $this->actionGetAdOrganizationInfo('MoneyList',$contractId);

        $amount = $MoneyList['amount'];
        $balance = $MoneyList['rent_amount']?$MoneyList['rent_amount']:0;//产品租用金额
        $delivery_amount = $MoneyList['delivery_amount'];//交付金额

        $budget = $amount+$addDrained;//预算=已经消费总额+准备新增点金额

        $data['balance'] = $balance;
        $data['budget'] = $budget;
        $data['usable'] = $balance-$amount;//可用余额



        $Code = null;
        $Msg= null;

        if($budget<=$balance){//预算需要小于产品租用金额才能消耗

            //坏味道修复

            $receivable = [];
            $data = $this->_contractService->getAdOrganizationInfo($contractId);

            //时间格式化成年月日 以防万一
            $EstablishTimeNow = date("Y-m-d",time());

            foreach ($data as $key=>$item){
                $receivable[$key]['EstablishTime'] = $item['startOn']?date("Y-m-d",$item['startOn']):$EstablishTimeNow;
                $receivable[$key]['BeginOn'] = $item['startOn'];
                $receivable[$key]['EndOn'] = $item['endOn'];
                $receivable[$key]['summaryReceived'] = $item['Money'];
            }

            $income = $receivable;
            // 开启事务
            $configDataBase = ContractEntity::getDb();
            $trans = $configDataBase->beginTransaction();
            try{
                $insertId = $this->_contractService->AddAdList($arr,$contractId);
                if($insertId === false){
                    $trans->rollBack();
                    return false;
                }

                //修复坏味道

                $trans->commit();

            }catch(\Exception $e){
                $trans->rollBack();
                return false;
            }

            if($insertId){
                $Code  = 0;
                $Msg = '增加成功';
            }

            $this->exportJson($data,$Code,$Msg);

        }else{
            $Code  = 400;
            ///$Msg = '超过预算'.abs($budget-$balance);
            $Msg = '投放金额大于广告投放款：'.abs($budget-$balance);
        }

        unset($data['Path']);

        $this->exportJson($data,$Code,$Msg);

    }


    /**
     * @sine 2017-6-21
     * @auth zhoud01@mingyuanyun.com
     * 合同可用余额
     */
    public function actionAdBalance($contractId=null)
    {

        $contractId = $this->getParam('contractId');
        $Id = $this->getParam('Id');

        $baseData = $this->_contractService->getContractInfo($contractId);

        $MoneyList = $this->actionGetAdOrganizationInfo('MoneyList',$contractId);

        $thisBalance = 0;

        if(!empty($Id)){
            $thisBalance = $MoneyList['idAndPrice'][$Id];
        }

        $Code = 0;
        $Msg= '';

        $amount = $MoneyList['amount'];
        $balance = $MoneyList['rent_amount']?$MoneyList['rent_amount']:0;//产品租用金额


        $data['balance'] = $balance;
        $usable = ($balance-$amount+$thisBalance);//可用余额
        $data['usable'] = round($usable*100)/100;

        $ServiceType = [
            '62f81bf4-fcf4-11e4-bed8-00155d02c832',//云客租用
            '62f81ca9-fcf4-11e4-bed8-00155d02c832'////云客增值服务 彭涛提出
        ];

        if(in_array($baseData['contract']['littler_category_id'],$ServiceType)){//云客租用
            $data['usable'] = 0;
        }

        $this->exportJson($data,$Code,$Msg);

    }


    /**
     * @sine 2017-6-15
     * @auth zhoud01@mingyuanyun.com
     * 修改广告记录
     */
    public function actionEditAdList($idToDelpath=null)
    {

        $Id = $this->getParam('Id');
        $contractId = $this->getParam('contractId');
        //坏味道修复

        $startOn = $this->getParam('startOn','post');
        $endOn = $this->getParam('endOn','post');
        $Money =  $this->getParam('Money','post');

        $DownloadUrl = null;
        $SaveName = null;
        $FileName = null;

        if(!empty($_FILES)){
            if($_FILES['file']['error']['file'] == UPLOAD_ERR_OK){//上传成功

                $uploadData = $this->actionUploadDocument('edit');
                $DownloadUrl = (empty($uploadData['data']['path'])?null:$uploadData['data']['path']);
                $SaveName = basename($DownloadUrl);
                $FileName = $_FILES['file']['name'];

            }
        }

        //坏味道修复

        $startOn = $startOn?strtotime($startOn):time();
        $endOn = $startOn?strtotime($endOn):time();

        $arr = [
            [
                'Id'=>$Id,
                //'Time'=>$Time,
                'startOn'=>$startOn,
                'endOn'=>$endOn,
                'Money'=>$Money,
                'DownloadUrl'=>$DownloadUrl,
                'SaveName'=>$SaveName,
                'FileName'=>$FileName,
            ],
        ];

        $addDrained = 0;

        foreach ($arr as $k=>$v){
            $addDrained+=$v['Money'];
        }

        $MoneyList = $this->actionGetAdOrganizationInfo('MoneyList',$contractId);

        $amount = $MoneyList['amount'];
        $balance = $MoneyList['rent_amount']?$MoneyList['rent_amount']:0;//产品租用金额
        $MoneyList['delivery_amount'];//交付金额
        $idAndPrice = $MoneyList['idAndPrice'];//id与消费金关系
        $thisPrice = $idAndPrice[$Id];//本条的金额

        $thisPrice = $Money?$thisPrice:0;//校正显示问题
        $budget = $amount+$addDrained;//预算=已经消费总额+准备新增的金额

        $data['balance'] = $balance;
        $data['budget'] = $budget-$thisPrice;
        $data['usable'] = $balance-$amount;//可用余额

        $Code = null;
        $Msg = null;

        if($budget-$thisPrice<=$balance){//预算需要小于产品租用金额才能消耗
            $insertId = $this->_contractService->EditAdList($contractId,$arr,$idToDelpath);
            $data['Id'] = $insertId;
            $Code = 0;
            $Msg = '修改成功';
        }else{
            $Code  = 400;
            $Msg = '投放金额大于广告投放款：'.abs($budget-$balance-$thisPrice);
        }

        unset($data['Path']);
        $this->exportJson($data,$Code,$Msg);
    }



    /**
     * @sine 2017-6-15
     * @auth zhoud01@mingyuanyun.com
     * 删除广告记录
     */
    public function actionDelAdList()
    {

        $Id = $this->getParam('Id');
        $contractId = $this->getParam('contractId');

        $ids = [$Id];
        if(is_array($Id)){
            $ids = $Id;
        }

        $Code = null;
        $Msg = null;
        $delData = [];

        foreach ($ids as $id){

            if(!empty($id)){

                $data = $this->_contractService->getAdOrganizationInfo($contractId);
                $downloadList = [];

                foreach ($data as $k=>$v){
                    $downloadList[$v['Id']] =$v['DownloadUrl'];
                }

                //验证id是否存在
                if(!array_key_exists($id,$downloadList)){
                    $Code = 400;
                    $Msg = 'Id:'.$id.'不存在';
                }else{
                    $delId = $this->_contractService->DelAdList($id,$contractId);

                    if($delId){
                        $syncObject = new MyscrmContractSyncDeleteDataRepository();
                        $syncObject->add('myscrm_ad_drain', 'Id', $Id);

                        $Code = 0;
                        $Msg = '删除成功';
                    }else{
                        $Code = 400;
                        $Msg = 'Id:'.$delId.'删除失败';
                    }

                }

            }

        }

        $this->exportJson($delData,$Code,$Msg);
    }


    /**
     * 获取合同性质
     */
    public function actionGetContractNatures()
    {
        $data = $this->_contractService->getContractNatures();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同类别
     */
    public function actionGetContractCategories()
    {
        $data = $this->_contractService->getContractCategories();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同大类
     */
    public function actionGetContractBigClass()
    {
        $data = $this->_contractService->getContractBigClass();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 根据大类id,获取合同小类
     * @param string $bigClassId 大类id
     */
    public function actionGetContractSmallClass($bigClassId = '')
    {
        if (empty($bigClassId)) {//是否传值为空
            $this->errorParam();
        }
        $data = $this->_contractService->getContractSmallClass($bigClassId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 根据关键字，获取产品名称列表
     * @param string $keyword 搜索关键字
     * @param int $limit 返回条数 传空：则全部返回
     * @param
     */
    public function actionGetProducts($keyword = '', $limit = '', $other = 0)
    {
        $data = $this->_contractService->getProducts($keyword, $limit, $other);

        //如果$other=0则新增一个其他选项
        $otherArr=[
            "application_id"=>"other",
            "application_name"=>"其他",
            "authorization_type"=>0,
            "applicationPrices"=>[]
        ];

        $other==0 && is_array($data) && array_push($data,$otherArr);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 根据关键字，获取应收款名称列表
     * @param string $keyword 搜索关键字
     */
    public function actionGetReceivableFundName($keyword = '')
    {
        $data = $this->_contractService->getReceivableFundName($keyword);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取款项小类
     */
    public function actionGetFundSmallClass($propertyId = '')
    {
        if (empty($propertyId)) {//合同id是否为空
            $this->errorParam();
        }
        $data = $this->_contractService->getFundSmallClass($propertyId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 特批授权界面获取合同select2控件下拉选项
     * @param string $keyword 搜索关键字
     * @param string $orgId 租户Id
     * @param string $page 分页
     */
    public function actionGetContractListForSepcialAuthorizeSelect2($keyword, $orgId, $limit)
    {
        $result = $this->_contractService->getContractListForSepcialAuthorizeSelect2($keyword, $orgId, $limit);
        $this->exportJson($result, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 违规合同界面获取合同select2控件下拉选项
     * @param string $keyword 搜索关键字
     * @param string $page 分页
     */
    public function actionGetContractListForViolatedContractSelect2($keyword, $limit)
    {
        $result = $this->_contractService->getContractListForViolatedContractSelect2($keyword, $limit);
        $this->exportJson($result, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取所有核算类型
     */
    public function actionGetBussAccountTypes()
    {
        $data = $this->_contractService->getBussAccountTypes();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同文档信息
     */
    public function actionGetContractDocuments()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }

        $data = $this->_contractService->getContractDocuments($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 保存合同文档信息
     */
    public function actionSaveContractDocuments()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $files = $this->getParam('files', 'post'); //获取post 文件数组
        $documents = $this->getParam('documents', 'post'); //获取文档信息数组

        $data = $this->_contractService->saveContractDocuments($contractId, $files, $documents);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取客户信息
     * @param string $keyword 搜索关键字
     */
    public function actionGetCustomerInfo($keyword = '')
    {
        $data = $this->_contractService->getCustomerInfo($keyword);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取业绩信息
     */
    public function actionGetSignAchievement()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $data = $this->_contractService->getSignAchievement($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 保存业绩修改
     */
    public function actionSaveSignAchievement()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        $signAchievements = $this->getParam('signAchievements', 'post'); //签约业绩列表
        $paymentAchievements = $this->getParam('paymentAchievements', 'post'); //回款业绩列表
        $drawProjectNumeric = $this->getParam('drawProjectNumeric', 'post'); //提成产品数
        $projectNumeric = $this->getParam('projectNumeric', 'post'); //项目数
        $achievementRemark = $this->getParam('achievementRemark', 'post'); //业绩备注
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $data = $this->_contractService->saveSignAchievement($contractId, $drawProjectNumeric, $signAchievements, $paymentAchievements, $projectNumeric, $achievementRemark);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取交付业绩信息
     */
    public function actionGetSignDely()
    {
        $contractId = $this->getParam('contractId', 'get');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $data = $this->_contractService->getSignDely($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 保存交付业绩修改
     */
    public function actionSaveSignDely()
    {
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $files = $this->getParam('files', 'post'); //获取post 文件数组
        $signDelys = $this->getParam('signDelys', 'post'); //获取业绩信息数组

        $data = $this->_contractService->saveSignDely($contractId, $files, $signDelys);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取最新合同编号
     * @param string $areaCode 区域代码
     * @param string $customerId 客户id
     * @param string $contractCode 合同编号
     */
    public function actionGetContractFlowCode($areaCode = '', $customerId = '', $contractCode = '')
    {
        $data = $this->_contractService->getContractFlowCode($areaCode, $customerId, $contractCode);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 导出合同
     */
    public function actionExportContract()
    {
        ob_end_clean();
        ini_set('max_execution_time', 600);
        ini_set('memory_limit', '512M');
        set_time_limit(600);
        $status = $this->getParam('status');     //合同状态  合同状态:0：草稿,1：提交复核,2：已审核  -1作废
        $property = $this->getParam('property'); //合同性质id
        $keyword = $this->getParam('keyword');   //关键字
        $areaId = $this->getParam('areaId');     //区域id
        $timeType = $this->getParam('timeType'); //时间类型
        $beginDate = $this->getParam('beginDate');   //开始时间
        $endDate = $this->getParam('endDate');     //截止时间
        $reportType = $this->getParam('reportType');     //报表类型
        $reportType = !empty($reportType) ? explode(',', $reportType) : [];
        $data = $this->_contractService->exportContract($status, $property, $keyword, $areaId, '', $timeType, $beginDate, $endDate, $reportType);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    public function actionDownExcel()
    {
        $fileName = CacheManage::getExportContract();
        Header("Location: $fileName");
        $this->exportJson($fileName, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 租期即将到期授权提醒
     * @param $expiredDays 过期天数：30、60
     * @return array|\yii\db\ActiveRecord[]
     */
    public function actionAuthorizationExpiredRemind()
    {
        $expiredDays = $this->getParam('expiredDays');
        $this->_contractService->authorizationExpiredRemind($expiredDays);
    }

    /**
     * 我的合同
     * @param integer $pageIndex 页码
     * @param integer $pageSize 页条数
     * @param string $sortBy 排序字段
     * @param int $status 合同状态  合同状态:0：草稿,1：提交复核,2：已审核  -1作废
     * @param string $property 合同性质id
     * @param string $sortBy 排序字段
     * @param boolean $sortAsc 是否升序
     * @param boolean $property 合同性质
     * @param integer $areaId 区域id
     * @param string $keyword 关键字
     */
    public function actionGetMyContractList($pageIndex = 1, $pageSize = 10, $sortBy = null, $sortAsc = '', $status = null, $property = null, $keyword = null, $areaId = null, $timeType = 0, $beginDate = '', $endDate = '')
    {
        $signPeopleId = Yii::$app->user->identity->userguid;
        $data = $this->_contractService->getContractList($pageIndex, $pageSize, $sortBy, $sortAsc, $status, $property, $keyword, $areaId, $signPeopleId, $timeType, $beginDate, $endDate);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 导出合同
     */
    public function actionExportMyContract()
    {
        ini_set('max_execution_time', 180);
        set_time_limit(180);
        $status = $this->getParam('status');     //合同状态  合同状态:0：草稿,1：提交复核,2：已审核  -1作废
        $property = $this->getParam('property'); //合同性质id
        $keyword = $this->getParam('keyword');   //关键字
        $areaId = $this->getParam('areaId');     //区域id
        $timeType = $this->getParam('timeType'); //时间类型
        $beginDate = $this->getParam('beginDate');   //开始时间
        $endDate = $this->getParam('endDate');     //截止时间
        $reportType = $this->getParam('reportType');     //报表类型
        $reportType = !empty($reportType) ? explode(',', $reportType) : [];
        $signPeopleId = Yii::$app->user->identity->userguid;
        $data = $this->_contractService->exportContract($status, $property, $keyword, $areaId, $signPeopleId, $timeType, $beginDate, $endDate, $reportType);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同id所有签约产品列表
     */
    public function actionGetContractApplicationList()
    {

        $contractId = $this->getParam('contractId', 'get');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }

        $data = $this->_contractService->getAuthorizationAchievementByContractId($contractId);//新业绩表

        foreach ($data as &$item){

            $item['application_id'] = $item['app_id'];//统一取值
            $item['price'] = $item['price_standard'];//统一取值

            $query = new ApplicationInfoEntity;
            $prodType = $query->find()
                ->select("in_other")
                ->where(['application_id' => $item['app_id']])
                ->asArray()
                ->one();

            $item['in_other'] = $prodType['in_other'];

            if($prodType['in_other'] == 1){
                //坏味道修复
                $item['other_application_id'] = $item['app_id'];
                $item['other_application_name'] = $item['application_name'];
                $item['application_id'] = "other";
                $item['application_name'] = "其他-" . $item["other_application_name"];
            }


        }

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }


    /**
     * 删除 [草稿,作废] 的合同
     * @param $id
     */
    public function actionDeleteContract()
    {
        $contractId = $this->getParam('contractId', 'post');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $data = $this->_contractService->deleteContract($contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /*
     *
     * Author yuyj
     * Date 2017-01-06
     * @apiVersion 1.0.0
     * @api {get} /api/index.php/contract/search 搜索合同
     * @apiGroup contract-controller
     *
     * @apiParam query {string} keyword 搜索关键字
     * @apiParam query {string} [pageNo] 页码
     * @apiParam query {string} [pageSize] 每页数量
     *
     * @apiResponse 200 {
     *  "retCode": 0,
     *  "errMsg": "",
     *  "data": {
     *      "contract_id": "39d07971-62e8-c784-7932-694fc39cb489",
     *      "contract_code{合同编号}": "1111111",
     *      "customer_name{客户简称}": "万科",
     *      "customer_full_name{客户全称}": "万科",
     *      "top_customer_name{顶级客户简称}": "万科集团",
     *      "sign_date{签约日期}": "2015-05-05 00:00:00",
     *      "sign_people_id{签约人ID}": "7091f686-f280-40f2-bbea-0f377e7ee225",
     *      "sign_amount{签约金额}": "1000000.00",
     *      "sign_people{签约人姓名}": "张进成",
     *      "email{邮箱}": "zhangjc@mysoft.com.cn",
     *      "mobile{手机号码}": "+8613871288992"
     *  }
     * }
     */
    public function actionSearch($keyword, $pageNo = 1, $pageSize = 10)
    {
        if (empty($keyword)) {
            $this->errorParam();
        }

        $data = $this->_contractService->search($keyword, $pageNo, $pageSize);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 导入还款
     */
    public function actionImportRepayment()
    {
        if (!isset($_FILES['file'])) {
            $this->exportJson([], -1, "未上传文件");
        }
        $filePath = $_FILES['file']['tmp_name'];
        /* @var $myscrmContractService MyscrmContractManageService */
        $myscrmContractService=\Yii::createObject(MyscrmContractManageService::className());
        $ret=$myscrmContractService->importRepayment($filePath);
        $this->exportJson($ret, $myscrmContractService->getErrCode(), $myscrmContractService->getErrMsg());
    }

    /**
     * 获取合同 签约金额 应结算金额 已结算金额
     */
    public function actionGetContractSignedReceivableReceived()
    {
        $contractId = $this->getParam('contractId', 'get');
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        $getContractManageModelByContractId = $this->_contractService->getContractManageListByContractId($contractId);//租户管理中的开通产品

        $getContractOrganizationInfo = $this->_contractService->getContractOrganizationInfo($contractId);
        $AuthorizeList = isset($getContractOrganizationInfo['AuthorizeList']) ? $getContractOrganizationInfo['AuthorizeList'] : [];

        //空数组校验
        $AuthorizeList=empty($AuthorizeList)?[]:$AuthorizeList;

        $received = 0;
        foreach ($AuthorizeList as $item){
            $received +=$item['SettlementAmount'];
        }

        if(!empty($contractId)){
            $data =[
                'signed'=>$getContractManageModelByContractId['sign_amount'],//签约金
                'receivable'=>$getContractManageModelByContractId['income_amount'],//应结算
                'received'=>$received,//已经结算
            ];
        }

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 获取合同可以授权信息
     */
    public function actionGetContractOrder()
    {
        $contractId = $this->getParam('contractId', 'get');
        if (empty($contractId)) {//是否传值为空update-contract
            $this->errorParam();
        }

        $getProductDatas = $this->_contractService->getProductDatas($contractId);
        $getTenantAuthorizeProductDatas = $this->_contractService->getTenantAuthorizeProductDatas();//租户管理中的开通产品
        array_column($getTenantAuthorizeProductDatas, 'UniqueName');
        $data = [];

        if(!empty($getProductDatas)){
            foreach ($getProductDatas as $key=>$getProductData){

                if($getProductData['provisioning_type'] == 1 || $getProductData['provisioning_type'] == null){//过滤自动的与provisioning_type类型为空
                    continue;
                }

                $data['sureAuthorizeList'][$key] = [
                    'applicationId'=>$getProductData['application_id'],
                    'contract_application_id'=>$getProductData['contract_application_id'],//合同开通的产品,可以当订单id用 TODO貌似不用这个思路了
                    'applicationName'=>$getProductData['application_name'],
                    'unique_name'=>$getProductData['unique_name'],
                    'contract_type'=>$getProductData['contract_type'],//合同属性(产品属性)，1新增，2增购，3续签';前台显示需注意在名字上补全
                    'provisioning_type'=>$getProductData['provisioning_type'],
                    'area_discount' => $getProductData['area_discount'],
                    'benchmark_amount' => $getProductData['price'],
                    'rent_period' => $getProductData['rent_period'],
                    'authorization_numeric' => $getProductData['authorization_numeric'],
                    'delivery_rules' => $getProductData['delivery_rules'],
                    'unit' => $getProductData['unit'],
                ];
            }
        }

        $result = [];
        if(!empty($data['sureAuthorizeList'])){
            //过滤去重
            foreach($data['sureAuthorizeList'] as $k=>$v){
                if(!isset($result[$v['applicationId']])){
                    $result[$v['applicationId']]=$v;
                }
            }
        }

        $result = array_values($result);
        $data['sureAuthorizeList'] = $result;
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    /**
     * 新增合同授权信息
     */
    public function actionAddContractOrder()
    {
        $arr = [
            'contract_id'=>$this->getParam('contractId', 'post'),//增加用 修改也要传合同id
            'id'=>$this->getParam('id', 'post'),//修改用 授权表id
            'application_id' => $this->getParam('application_id', 'post'),
            'total_num' => $this->getParam('total_num', 'post'),
            'establish_time' => $this->getParam('establish_time', 'post'),
            'begin_on' => $this->getParam('begin_on', 'post'),
            'end_on' => $this->getParam('end_on', 'post'),
            'settlement_amount' => $this->getParam('settlement_amount', 'post',0),
            'sign_amount' => $this->getParam('sign_amount', 'post',0),
            'product_type' => $this->getParam('contract_type', 'post'),
            'contract_application_id' => $this->getParam('contract_application_id', 'post'),
            'performance_accounting_time' => $this->getParam('performance_accounting_time', 'post'),
            'organization_id' => $this->getParam('organization_id', 'post'),
            'order_code' => $this->getParam('order_code', 'post'),
        ];
        $contract_application = [
            'area_discount' => $this->getParam('area_discount','post'),
            'current_discount' => $this->getParam('current_discount','post'),
            'current_real_discount' => $this->getParam('current_real_discount','post'),
            'benchmark_amount' => $this->getParam('benchmark_amount','post'),
            'settlement_scale' => $this->getParam('settlement_scale','post'),
            'contract_type' => $this->getParam('contract_type','post'),
            'settlement_type' => $this->getParam('settlement_type','post'),
            'discount' => $this->getParam('discount','post'),
        ];
        $old_author_infos = [];
        $old_myscrm_contract = [];
        if($arr['id']){
            $old_author_info = MyscrmOrganizationToAuthorizeEntity::find()->where(['Id'=>$arr['id']])->asArray()->one();
            if($old_author_info){
                $old_myscrm_contract = MyscrmContractRepository::getContractByContractId($old_author_info['ContractId']);
                if( $old_myscrm_contract['BeginOn']==date('Y-m-d H:i:s',strtotime($arr['begin_on'])) && $old_myscrm_contract['EndOn'] == date('Y-m-d H:i:s',strtotime($arr['end_on'])) && $old_myscrm_contract['PerformanceAccountingTime'] == date('Y-m-d H:i:s',strtotime($arr['performance_accounting_time']))){
                    $old_author_infos = array();
                }else{
                    $old_author_infos = MyscrmOrganizationToAuthorizeEntity::find()->where(['ContractId'=>$old_author_info['ContractId']])->asArray()->all();
                }
//                $applicationInfoAtContractDB = MyscrmContractApplicationService::getApplicationInfoByApplicationId($old_author_info['application_info_id']);
//                $revenue = $this->_contractService->getRevenueBy($arr['contract_id'],$old_myscrm_contract['BeginOn'],$old_myscrm_contract['EndOn'],$old_myscrm_contract['PerformanceAccountingTime'],$applicationInfoAtContractDB['buss_type_id']);
            }
        }

        $applicationInfoAtContractDB = MyscrmContractApplicationService::getApplicationInfoByApplicationId($arr['application_id']);

        $contractModel = ContractManageRepository::getContractManageModelByContractId($arr['contract_id']); //获取model

        $revenue = $this->_contractService->getRevenueBy($arr['contract_id'],$arr['begin_on'],$arr['end_on'],$arr['performance_accounting_time'],$applicationInfoAtContractDB['buss_type_id']);

        $contractApiLogModel = new contractApiLogModel();
        $contractApiLogModel->log_type = 1;
        $contractApiLogModel->call_line = __LINE__;
        $contractApiLogModel->call_method = __METHOD__;
        $contractApiLogModel->call_parametes =json_encode($arr,JSON_UNESCAPED_UNICODE);
        $contractApiLogModel->return_data = json_encode($revenue,JSON_UNESCAPED_UNICODE);
        $contractApiLogModel->return_code = $this->_revenueService->getErrCode();
        $contractApiLogModel->error_msg = $this->_revenueService->getErrMsg();
        $contractApiLogModel->call_user = isset(\Yii::$app->user->identity->userguid) ? \Yii::$app->user->identity->userguid : '';
        $contractApiLogModel->maintain_remark = '开通信息修改产品相关';
        $this->_logService->addContractApiLogRecord($contractApiLogModel);

        $arr['openType'] = 'Manual';

        $this->_contractService->getContractInfo($arr['contract_id']);

        //租户管理中的开通产品
        $arr['contract_num'] = $this->_contractService->getContractNum($arr['contract_id']);

        //时间格式化成年月日 以防万一
        $arr['establish_time'] = date("Y-m-d",strtotime($arr['establish_time']));

        //格式化租期
        $rent_period = (strtotime($arr['end_on'])-strtotime($arr['begin_on']))/3600/24/30;
        $rent_period = $this->formatLease($rent_period);
        $arr['rent_period'] = $rent_period;

        $matching_rule = $applicationInfoAtContractDB['matching_rule'];
        $delivery_rules = $applicationInfoAtContractDB['delivery_rules'];

        $arr['matching_rule'] = $applicationInfoAtContractDB['matching_rule'];
        $arr['delivery_rules'] = $applicationInfoAtContractDB['delivery_rules'];

        $myscrmContractApplicationInfo = $this->authorizationValidateRules($arr);

        $arr['contract_application_id'] = $myscrmContractApplicationInfo['contract_application_id'];

        //已经有这种订单不可以增加
        if(empty($myscrmContractApplicationInfo)){
            //有漏洞,改合同属性就可以增加
            $data  = false;
            $Code  = 400;
            $Msg = '没有这个订单不可开通授权';
            $this->exportJson($data,$Code,$Msg);
        }

        $AlreadyAuthorized = $this->_contractService->getContractOrganizationInfo($arr['contract_id'],$getType = true);

        $alreadyHasApp = [];

        foreach($AlreadyAuthorized as $k=>$v){//依据租期,产品,产品,类型进行分组
            $time = (strtotime($v['endOn'])-strtotime($v['beginOn']))/3600/24/30;
            $lease = $this->formatLease($time);
            if(!isset($alreadyHasApp[$v['ApplicationId'].$lease.$v['ProductType']])){
                $alreadyHasApp[$v['ApplicationId'].'--'.$lease.'--'.$v['ProductType']]=$v;
            }
        }

        $alreadyHasAppKey = array_keys($alreadyHasApp);

        $commitLease = (strtotime($arr['end_on'])-strtotime($arr['begin_on']))/3600/24/30;
        $commitLease = $this->formatLease($commitLease);
        $commitApp = $arr['application_id'].'--'.$commitLease.'--'.$arr['product_type'];

        $res =in_array($commitApp,$alreadyHasAppKey);

        if($res&&empty($arr['id'])&&($matching_rule == 2 && $delivery_rules == 1 )){//|| $matching_rule == 3
            //有漏洞,改合同属性就可以增加
            $data  = false;
            $Code  = 400;
            $Msg = '该类型产品已经授权';
            $this->exportJson($data,$Code,$Msg);
        }

        $ykPropertyId = [
            ContractPropertyEntity::MYYK_PROPERTY_JOINT_SIGNED_SETTLEMENT_OPERATION_ID,//明源签约-直属
            ContractPropertyEntity::MY_PROPERTY_DIRECTLY_OPERATION_ID,//明源签约-联营
            ContractPropertyEntity::MY_PROPERTY_JOINT_OPERATION_ID,//联营签约-云客结算
        ];

        $ykPropertyClassId = [
            ContractPropertyEntity::MYYK_PROPERTY_DIRECTLY_UNDER_ID,//云客签约-直属
            ContractPropertyEntity::MYYK_PROPERTY_JOINT_OPERATION_ID,//云客签约-直属区域
            ContractPropertyEntity::MYYK_PROPERTY_DIRECT_SALES_ID,//云客直销
        ];

        //获取合同性质
        $contractPropertyId = $this->_contractService->getContractNature($arr['contract_id']);
        $arr['is_joint'] = in_array($contractPropertyId,$ykPropertyId);
        // 开启事务
        $configDataBase = ContractEntity::getDb();
        $trans = $configDataBase->beginTransaction();
        try{

            //更新合同产品信息

            $myscrmContractApplicationInfo = ContractApplicationEntity::find()->where(['contract_application_id' => $arr['contract_application_id']])->one();
            $myscrmContractApplicationInfo->load($contract_application, '');
            $resultAdd = $myscrmContractApplicationInfo->save();
            if($resultAdd === false){
                $trans->rollBack();
                $this->exportJson($resultAdd, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
                return false;
            }


            $resultAdd = $this->_contractService->addAuthorizeByOrganizationId($arr);//租户管理中的开通产品

            if($resultAdd === false){
                $trans->rollBack();
                $this->exportJson($resultAdd, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
                return false;
            }

//            $SummaryArr = $this->actionGetContractOrderSummary($arr['contract_id'],$toReceivable = true);
            $SummaryArr = $this->_contractService->getContractOrderSummaryById($arr['contract_id'],$toReceivable = true);
            $this->_contractService->putLog('handadd_summary=>'.var_export($SummaryArr,true),__METHOD__,$SummaryArr);
            //明源签约-直属,明源签约-联营,联营签约-云客结算 这三类才写应收
            if(in_array($contractPropertyId,$ykPropertyId)){//将产品信息写入业绩表

                $model = new ContractReceivableService;
                $resultAdd = $model->saveContractReceivableByEstablish($SummaryArr,$arr['contract_id']);

                if($resultAdd === false){
                    $trans->rollBack();
                    $this->exportJson($resultAdd, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
                    return false;
                }
            }

            //云进货后主动推送进货产品信息
            $this->_contractService->sendContractApplication($arr['contract_id'], $arr['application_id'], $arr['total_num']);

            $trans->commit();
            $data  = true;
        }catch(\Exception $e){
            $trans->rollBack();
            $this->exportJson('开通信息授权事物异常', $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
            return false;
        }

        try{
            if(in_array($contractPropertyId,$ykPropertyId)) {
                $SummaryArrForLease = $this->actionGetContractOrderSummaryByDateAndLease($arr['contract_id'],$toReceivable = true);
                $this->_contractService->submitRevenueByEstablish($SummaryArrForLease,$arr['contract_id'],'',$revenue,$old_myscrm_contract,$old_author_infos);
            }
            if(in_array($contractPropertyId,$ykPropertyClassId)&&$contractModel->effect_date>='2018-01-01'){//云客类 开通增加收入
                $SummaryArrForLease = $this->actionGetContractOrderSummaryByDateAndLease($arr['contract_id'],$toReceivable = true);
                $this->_contractService->submitRevenueByEstablish($SummaryArrForLease,$arr['contract_id'],'yk',$revenue,$old_myscrm_contract,$old_author_infos);
            }
        }catch (\Exception $e){
            $this->exportJson($data, 0, $e->getMessage());
        }
        $this->exportJson($data, $this->_contractService->getErrCode(), '');
    }

    /**
     * 授权规则校验
     * @author zhoud01
     * @since 2017-8-2
     *
     */
    public function authorizationValidateRules($arr){

        $applicationInfoAtContractDB = MyscrmContractApplicationService::getApplicationInfoByApplicationId($arr['application_id']);

        $matching_rule = $applicationInfoAtContractDB['matching_rule'];

        //租户管理中的开通产品
        $arr['contract_num'] = $this->_contractService->getContractNum($arr['contract_id']);
        //时间格式化成年月日 以防万一
        $arr['establish_time'] = date("Y-m-d",strtotime($arr['establish_time']));
        $rent_period = (strtotime($arr['end_on'])-strtotime($arr['begin_on']))/3600/24/30;
        //格式化租期
        $rent_period = $this->formatLease($rent_period);
        $contract_type = $arr['product_type'];

        $myscrmContractApplicationEntity = new ContractApplicationEntity();

        $where1 = [
            'contract_id' => $arr['contract_id'],
            'application_id' => $arr['application_id'],
            'rent_period' => $rent_period,
            'contract_type' => $contract_type,
        ];

        $where2 = [
            'contract_id' => $arr['contract_id'],
            'application_id' => $arr['application_id'],
            'contract_type' => $contract_type,
        ];


        $where3 = [
            'contract_id' => $arr['contract_id'],
            'application_id' => $arr['application_id'],
        ];

        $where = [];

        if($matching_rule == 1){
            $where = $where1;
        }

        if($matching_rule == 2){
            $where = $where2;
        }

        if($matching_rule == 3){
            $where = $where3;
        }

        return $myscrmContractApplicationEntity::find()->where($where)->asArray()->one();

    }


    /**
     * 租期计算公式
     * @author zhoud01
     * @since 2017-8-2
     *
     */
    public function formatLease($time)
    {
        $time = $time<1?1:$time;
        // 修复坏味道
        return (int)round($time);

    }

    /**
     * 获取合同授权按日期汇总
     */
    public function actionGetContractOrderSummary($contractId,$toReceivable = false)
    {

        if(empty($toReceivable)){
            $contractId = $this->getParam('contractId', 'get');
        }

        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }

        $contractNum = $this->_contractService->getContractNum($contractId);//租户管理中的开通产品

        //改个注释方便提交

        $GetContractOrderSummaryInfo = $this->_contractService->GetContractOrderSummary($contractNum);//租户管理中的开通产品

        $arr = [];
        foreach ($GetContractOrderSummaryInfo as $key=>$item){

            $application_id = $item['ApplicationId'];
            $application_info_id = $item['application_info_id'];//合同库产品info

            //需要做兼容处理 $application_id 找不到结果 就用 $apply_application_id
            $ApplicationInfo = $this->_contractService->GetApplicationInfoByApplicationId($application_id);
            $ApplicationInfo = empty($ApplicationInfo)?$this->_contractService->GetApplicationInfoByApplicationId($application_info_id):$ApplicationInfo;

            $applicationInfo = MyscrmApplicationRepository::getApplicationByApplicationId($application_id);

            $appDataInfo = MyscrmContractApplicationService::getApplicationInfoByAuthorizeUniqueName($applicationInfo->UniqueName,$item['IsQdAdvanced']);//查真名用

            $FriendlyName = $applicationInfo->FriendlyName;

            $application_name = $appDataInfo['application_name'];


            $contractAndApp = ContractApplicationRepository::getContractApplicationAppId($item['ContractApplicationId']);//订单产品信息
            $applicationInfoAtContractDB = MyscrmContractApplicationService::getApplicationInfoByApplicationId($contractAndApp->application_id);//所有产品

            if(!empty($FriendlyName)) {
                
                $item['applicationName'] = $applicationInfoAtContractDB['application_name'];
                if(empty($applicationInfoAtContractDB['application_name'])){
                    $item['applicationName'] = $FriendlyName;
                }
            }


            if(empty($applicationInfo)){
                $item['applicationName'] = $ApplicationInfo['application_name'];
            }
            
            if(empty($FriendlyName) && empty($application_name)){
                $item['applicationName'] = '';
            }

            $item['summaryReceived'] = $item['SettlementAmount'];
            $item['date'] = date("Y-m-d",strtotime($item['EstablishTime']));

            $item['buss_type_id'] = $ApplicationInfo['buss_type_id'];

            if(empty($item['buss_type_id'])&&!empty($toReceivable)){
                $data  = false;
                $Code  = 400;
                $Msg = $ApplicationInfo['application_name'].':<br />业务收入项字段值为0或者为空';
                $this->exportJson($data,$Code,$Msg);
            }

            $arr[$key] =$item;
        }

        $result = [];
        $appName = [];
        $productType = [];

        foreach($arr as $v){
            if(!isset($result[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']])){
                $result[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']]=$v;
                $result[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']]['contractId'] = $contractId;
                $appName[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']][$v['applicationName']] = 1;
                $productType[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']][$v['ProductType']] = 1;
                $result[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']]['ProductType'] = join(',',array_keys($productType[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']]));
            }else{
                $result[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']]['summaryReceived']+=$v['summaryReceived'];
                $result[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']]['ApplicationId'].=','.$v['ApplicationId'];
                $productType[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']][$v['ProductType']] = 1;
                $result[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']]['ProductType'] = join(',',array_keys($productType[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']]));
                $result[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']]['Id'].=','.$v['Id'];
                $appName[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']][$v['applicationName']] = 1;
                $result[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']]['applicationName'] = join(',',array_keys($appName[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']]));
                $result[$v['PerformanceAccountingTime'].'--'.$v['buss_type_id']]['contractId'] = $contractId;
            }
        }

        $data['summaryAuthorizeList'] = $result;

        if(!empty($toReceivable)){
            return $result;
        }

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }



    /**
     * 获取合同授权按日期&租期汇总
     */
    public function actionGetContractOrderSummaryByDateAndLease($contractId,$toReceivable = false)
    {
        if(empty($toReceivable)){
            $contractId = $this->getParam('contractId', 'get');
        }

        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }

        $contractNum = $this->_contractService->getContractNum($contractId);//租户管理中的开通产品

        $GetContractOrderSummaryInfo = $this->_contractService->GetContractOrderSummary($contractNum);//租户管理中的开通产品

        $arr = [];
        foreach ($GetContractOrderSummaryInfo as $key=>$item){

            $application_id = $item['ApplicationId'];
            $application_info_id = $item['application_info_id'];//合同库产品info

            //需要做兼容处理 $application_id 找不到结果 就用 $apply_application_id
            $ApplicationInfo = $this->_contractService->GetApplicationInfoByApplicationId($application_id);
            $ApplicationInfo = empty($ApplicationInfo)?$this->_contractService->GetApplicationInfoByApplicationId($application_info_id):$ApplicationInfo;

            $item['applicationName'] = $ApplicationInfo['application_name'];
            $item['summaryReceived'] = $item['SettlementAmount'];
            $item['date'] = date("Y-m-d",strtotime($item['EstablishTime']));
            $item['signAmount'] = $item['SignAmount'];
            $item['buss_type_id'] = $ApplicationInfo['buss_type_id'];

            if(empty($item['buss_type_id'])){
                $data  = false;
                $Code  = 400;
                $Msg = $ApplicationInfo['application_name'].':<br />业务收入项字段值为0或者为空';
                $this->exportJson($data,$Code,$Msg);
            }
            $arr[$key] =$item;
        }

        $result = [];
        foreach($arr as $v){

            if(!isset($result[$v['PerformanceAccountingTime'].'--'.$v['BeginOn'].'--'.$v['EndOn'].'--'.$v['buss_type_id']])){
                $result[$v['PerformanceAccountingTime'].'--'.$v['BeginOn'].'--'.$v['EndOn'].'--'.$v['buss_type_id']]=$v;
                $result[$v['PerformanceAccountingTime'].'--'.$v['BeginOn'].'--'.$v['EndOn'].'--'.$v['buss_type_id']]['contractId'] = $contractId;
            }else{
                $result[$v['PerformanceAccountingTime'].'--'.$v['BeginOn'].'--'.$v['EndOn'].'--'.$v['buss_type_id']]['summaryReceived']+=$v['summaryReceived'];
                $result[$v['PerformanceAccountingTime'].'--'.$v['BeginOn'].'--'.$v['EndOn'].'--'.$v['buss_type_id']]['signAmount']+=$v['signAmount'];
                $result[$v['PerformanceAccountingTime'].'--'.$v['BeginOn'].'--'.$v['EndOn'].'--'.$v['buss_type_id']]['ApplicationId'].=','.$v['ApplicationId'];
                $result[$v['PerformanceAccountingTime'].'--'.$v['BeginOn'].'--'.$v['EndOn'].'--'.$v['buss_type_id']]['ProductType'].=','.$v['ProductType'];
                $result[$v['PerformanceAccountingTime'].'--'.$v['BeginOn'].'--'.$v['EndOn'].'--'.$v['buss_type_id']]['Id'].=','.$v['Id'];
                $result[$v['PerformanceAccountingTime'].'--'.$v['BeginOn'].'--'.$v['EndOn'].'--'.$v['buss_type_id']]['applicationName'].=','.$v['applicationName'];
                $result[$v['PerformanceAccountingTime'].'--'.$v['BeginOn'].'--'.$v['EndOn'].'--'.$v['buss_type_id']]['contractId'] = $contractId;
            }

        }
        
        $result = array_values($result);
        
        $data['summaryAuthorizeList'] = $result;

        if(!empty($toReceivable)){
            return $result;
        }

        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }


    /**
     * 更新合合同签约的产品
     * @author zhoud01
     * @since 2017-9-20
     *
     */
    public function actionUpdateProduct(){

        $arr = [

            'contract_application_id' => $this->getParam('contract_application_id', 'post'),
            'application_id' => $this->getParam('application_id', 'post'),
            'price' => $this->getParam('price', 'post'),
            'unit' => $this->getParam('unit', 'post'),
            'authorization_type' => $this->getParam('authorization_type', 'post'),
            'authorization_numeric' => $this->getParam('authorization_numeric', 'post'),
            'rent_period' => $this->getParam('rent_period', 'post'),
            'amount' => $this->getParam('amount', 'post'),

            'modified_by' => $_SESSION['__id'],//需要修改成当前使用者
            'modified_on' => date("Y-m-d",time()),//需要修改成当前时间

            'is_standard' => $this->getParam('is_standard', 'post'),//需要修改成当前时间

            'contract_type' => $this->getParam('contract_type', 'post'),//需要修改成当前时间
            'settlement_type' => $this->getParam('settlement_type', 'post'),//需要修改成当前时间
            'settlement_scale' => $this->getParam('settlement_scale', 'post'),//需要修改成当前时间

            'discount_rate' => $this->getParam('discount_rate', 'post'),//折扣率
            'discount' => $this->getParam('discount', 'post'),//折扣
            'other_application_id' => $this->getParam('other_application_id', 'post'),//折扣
            'benchmark_amount' => $this->getParam('benchmark_amount','post'),//结算基准价
        ];

        $contractAndApp = ContractApplicationRepository::getContractApplicationAppId($arr['contract_application_id']);//订单产品信息

        $contractAndApp->application_id = $arr['application_id']=='other'?$arr['other_application_id']:$arr['application_id'];
        $contractAndApp->price = $arr['price'];
        $contractAndApp->unit = $arr['unit'];
        $contractAndApp->authorization_type = $arr['authorization_type'];
        $contractAndApp->authorization_numeric = $arr['authorization_numeric'];
        $contractAndApp->rent_period = $arr['rent_period'];
        $contractAndApp->amount = $arr['amount'];
        $contractAndApp->modified_by = $arr['modified_by'];
        $contractAndApp->modified_on = $arr['modified_on'];
        $contractAndApp->is_standard = $arr['is_standard'];
        $contractAndApp->contract_type = $arr['contract_type'];
        $contractAndApp->settlement_type = $arr['settlement_type'];
        $contractAndApp->settlement_scale = $arr['settlement_scale'];
        $contractAndApp->discount_rate = $arr['discount_rate'];
        $contractAndApp->discount = $arr['discount'];
        $contractAndApp->benchmark_amount = $arr['benchmark_amount'];

        $res = $contractAndApp->save();

        $retCode = empty($res)?-1:0;

        $application = ContractApplicationRepository::getStandardContractApplicationByContractApplicationId($arr['contract_application_id']);

        if ($application["in_other"] == 1) {
            $application["other_application_id"] = $application["application_id"];
            $application["other_application_name"] = $application["application_name"];
            $application["application_id"] = "other";
            $application["application_name"] = "其他-" . $application["other_application_name"];
        }

        $res = $res?$application:false;
        $this->exportJson($res, $retCode, $this->_contractService->getErrMsg());

    }


    public function actionAddRevenue(){
        $this->exitIfNotPost();
        $contractId = $this->getParam('contractId', 'post'); //合同id
        $revenue = $this->getParam('revenue', 'post'); //合同id
        $accountCompanyId = $this->getParam('accountCompanyId', 'post'); //帐套公司id
        if (empty($contractId)) {//是否传值为空
            $this->errorParam();
        }
        try{
            $revenueId = $this->_contractService->submitRevenue($contractId, $accountCompanyId, $revenue);
        }catch (\Exception $e){
            $this->exportJson(false, $e->getTraceAsString(), $e->getMessage());
        }
        $data = $this->_contractService->getContractRevenueByRevenueId($revenueId,$contractId);
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

    public function actionDownloadContractDocStoreTemplate(){
        $outName = '纸质合同存放信息导入模板';
        $ext = 'xlsx';
        $file = dirname(\Yii::$app->basePath) . "/files/template/xls/{$outName}.{$ext}";
        $fp = fopen($file, "rb");
        header("Expires: 0");
        header("Content-Type: xlsx");
        header("Content-Disposition: attachment; filename={$outName}.{$ext}");
        fpassthru($fp);
        exit();
    }


    public function actionImportContractDocStore(){
        $data = $this->_contractService->importContractDocsStoreInfoExcel();
        $this->exportJson($data, $this->_contractService->getErrCode(), $this->_contractService->getErrMsg());
    }

}
